package com.hermes.comics.data;

import android.text.TextUtils;

import java.net.URLEncoder;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Issue extends Item<IssueTag> implements Comparable<Issue> {

  public Issue() {
    super("ISSUE");
  }

  String paddedKey() {
    String number = ""; 
    try {
      number = getTagValue(IssueTag.KEY); 
      return String.format("%05d", Integer.valueOf(number));
    } catch (NumberFormatException e) {
      return number;
    }
  }

  public Calendar getReadDate() {
    Calendar calendar = Calendar.getInstance();

    String read = IssueTag.READ.value(this);
    if (read == null) return calendar;

    String[] date = read.split("\\|");
    if (date.length == 3) {
      try {
        calendar.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]));
      } catch (NumberFormatException ex) { }
    }

    return calendar;
  }

  @Override
  public int compareTo(Issue o) {
    return this.paddedKey().compareTo(o.paddedKey());  
  }

  public String verbose() {
    StringBuilder buffer = new StringBuilder();
    buffer.append("  {\n");
    buffer.append(verbose("    "));
    buffer.append("  }\n");
    return buffer.toString();
  }

  @Override
  public List<String> row() {
    Map<String, String> fields = new TreeMap<String, String>();
    for (IssueTag tag : IssueTag.values()) {
      String value = tag.isBoolValue() ? getTagValue(tag, "N") : getTagValue(tag, "");
      fields.put(String.format("%4d", tag.index()), value.replace("#", " "));
    }
    return new ArrayList<String>(fields.values());
  }

  public String serialize() {
    StringBuilder builder = new StringBuilder();
    for (IssueTag tag : IssueTag.values()) {
      builder.append(tag.toString());
      builder.append("#");
      builder.append(getTagValue(tag, ""));
      builder.append("\t");
    }
    return builder.toString().trim();
  }

  public static Issue unserialize(String input) {
    Issue issue = new Issue();
    for (String fields : input.split("\t")) {
      String[] tagpair = fields.split("#");
      String value = "";
      for (int i = 1; i < tagpair.length; ++i) {
        value += tagpair[i] + " ";
      }
      issue.setTag(IssueTag.getTagByString(tagpair[0]), value.trim());
    }
    return issue;
  }

  @Override
  public String toString() {
    return getTagValue(IssueTag.KEY);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Issue) {
      Issue other = (Issue) obj;

      if (this.getTagValue(IssueTag.SERIE_KEY).equals(other.getTagValue(IssueTag.SERIE_KEY))) {
        return this.getTagValue(IssueTag.KEY).equals(other.getTagValue(IssueTag.KEY));
      } else {
        return false;
      }
    }

    return false;
  }
}
